/*
 * This file contains function and functionality for the student group
 */

var grpMembers = new Array();   // array with groupmembers studnr
var grpName = null;             // groupname
var ingrp = null;               // if user in group


/*
 * This function sets the groupmembers and groupname and if the user is in group or not
 */
function getGroup() {        
    if(ingrp == null) {
        $.ajax ({
            url : 'higface/student/library/getGroup.php',
            type : 'POST',
            success : function (tmp) {
                data = eval ('('+tmp+')');
                if(data.error){   // if the user is not in a group
                    ingrp = false;  // set the user to not be in a grp local              
                    displayList();  // displays the list
                } else {
                    ingrp = true;   // if the user is in a grp set it to true
                    grpName = data[1][1];   // set the groupname
                    for(y in data[0]){      //add groupmembers to group
                        grpMembers.push(data[0][y][1]);
                    }                                 
                    displayList();      // displays the list
                }            
            }
        });
    } else {        
        displayList();  // if the function already have been executed then just display list
    }
}

/*
 * This function will create the group
 */
function createGroup() {
    var name = document.getElementById('createname').value; // checks if the name is long enough
    if(name.length < 6) {
        alert('Navnet på gruppen må være lengre enn 6 bokstaver')
        return;
    }       
    $.ajax ({
        url : 'higface/student/library/addGroup.php',
        type : 'POST',
        data: {
            grpname: name
        },
        success : function (tmp) {
            data = eval ('('+tmp+')');
            if(data.error){
                alert(data.error);
                return;
            }
            ingrp = null;   // sets the ingroup to null so the globals can be set
            $('body > section').load ('pages/viewAllStudents.php'); // reload the content
        }
    });   
}

/*
 * This function creates a dialog so the user can create a group
 */
function createGroupDialog() {    
    // Create and load the content of the login dialog, then make it a dialog
    createDialog = $('<div></div>').load('dialogs/createGroup.php', function () {
        
        // Run this code when the content of the dialog has loaded                          
        // When the log in button is pressed, run the login method
        $('form.createGroup input[type="button"]').click (function() {
            createGroup();                  // runs the createGroup function
            createDialog.dialog('close');   // then close the dialog  
        });
        // Open the login dialog
            
        createDialog.dialog('open');
    }).dialog({
        autoOpen: false,
        position: [500,200],
        width: 350,
        title: 'Skriv inn navn på bacheloroppgave gruppen du er i ferd med å opprette',
        close: function (event, ui) {   // add close event
            $(this).remove();
        }
    });
    // Find the dialog and open it (Note, this doesn't work when creating the dialog on the fly so we need both)
    $('.createGroup').parent().dialog('open');
}

/*
 * This function will delete the group and all of its information
 */
function deleteGroup() {
    $.ajax ({
        url : 'higface/student/library/removeGroup.php',
        type : 'POST',
        success : function (data) {
            if(data.error){
                alert(data.error);
                return;
            }
            grpName = null;
            ingrp = null;   // sets to null so the globals can be reset
            grpMembers.length = 0;  // deletes all the group members in the array
            $('body > section').load ('pages/viewAllStudents.php'); // reload content
        }
    });
}

/*
 * This function creates a dialog to delete the group
 */
function deleteGroupDialog() {
    // Create and load the content of the login dialog, then make it a dialog
    deleteDialog = $('<div></div>').load('dialogs/deleteGroup.php', function () {
        
        // Run this code when the content of the dialog has loaded                          
        // When the log in button is pressed, run the login method
        $('form.deleteGroup input[name="accept"]').click (function() {
            deleteGroup();                  // if user click yes the delete group
            deleteDialog.dialog('close');   //close dialog 
        });
        
        $('form.deleteGroup input[name="deny"]').click (function() {
            deleteDialog.dialog('close');            // if user click no then close dialog
        });
        // Open the login dialog
            
        deleteDialog.dialog('open');
    }).dialog({
        autoOpen: false,
        position: [500,200],
        width: 350,
        title: 'Du er i ferd med å slette gruppen, dette vil medføre at all informasjon om gruppen og medlemmer blir slettet, vil du fortsette?',
        close: function (event, ui) {   // add close event
            $(this).remove();
        }
    });
    // Find the dialog and open it (Note, this doesn't work when creating the dialog on the fly so we need both)
    $('.deleteGroup').parent().dialog('open');
}

/*
 * This function updates the groupname
 */
function updateGroup() {
    var name = document.getElementById('updatename').value;     // get the new name from dialog
    if(name.length < 6) {                                       // checks if its long enough
        alert('Navnet på gruppen må være lengre enn 6 bokstaver')
        return;
    }       
    $.ajax ({
        url : 'higface/student/library/updateGroup.php',
        type : 'POST',
        data: {
            grpname: name
        },
        success : function (data) {
            if(data.error){
                alert(data.error);
                return;
            }
            grpName = name;         // sets the new name
            $('body > section').load ('pages/viewAllStudents.php'); //reload content
        }
    });  
}

/*
 * This function creates a dialog to update group name
 */
function updateGroupDialog() {
    // Create and load the content of the login dialog, then make it a dialog
    updateDialog = $('<div></div>').load('dialogs/updateGroup.php', function () {
        
        // Run this code when the content of the dialog has loaded                          
        // When the log in button is pressed, run the login method
        $('form.updateGroup input[type="button"]').click (function() {
            updateGroup();                  // updates the name
            updateDialog.dialog('close');   //close the dialog
        });
        // Open the login dialog
            
        updateDialog.dialog('open');
    }).dialog({
        autoOpen: false,
        position: [500,200],
        width: 350,
        title: 'Skriv inn nytt navn til gruppen din!',
        close: function (event, ui) {   // add close event
            $(this).remove();
        }
    });
    // Find the dialog and open it (Note, this doesn't work when creating the dialog on the fly so we need both)
    $('.updateGroup').parent().dialog('open');
}

/*
 * This function add a member to the group
 */
function add_member(item) { // sends the icon tag
    $.ajax ({
        url : 'higface/student/library/addMember.php',
        type : 'POST',
        data: {
            studid: item.parentNode.name    // get the student number 
        },
        success : function (tmp) {    
            data = eval ('('+tmp+')');
            if(data.error){
                alert(data.error);
                return;
            }
            var name = item.nextSibling.innerHTML;  //get the name of the student
            grpMembers.push(item.parentNode.name);  // add student to group array
            message(name, " ble lagt til!");                      // display add message
            item.setAttribute("onclick",'remove_member("'+name+'","'+item.parentNode.name+'");');  // add remove onclick event
            item.src = "LnF/x_21x21.png";
            var grpForm = document.getElementById('yourGroup'); // insert the list item above the buttons in group form
            var before = grpForm.getElementsByTagName("button");
            grpForm.insertBefore(item.parentNode, before[0]);
        }
    });
}

/*
 * This function removes a member from the group
 */
function remove_member(item, studnr) {  
    if(grpMembers.length == 1) {    // if the group only have one member, then the member will
        deleteGroupDialog();        // be the user, so delete the group
    } else {
        $.ajax ({
            url : 'higface/student/library/removeMember.php',
            type : 'POST',
            data : {
                memberid: studnr
            },
            success : function (data) {
                if(studnr == $(document).data ('uid')) {    // if the student the user wants to remove
                    ingrp = null;                           //is himself then remove him from the group
                    grpMembers.length = 0;                  // and reset the globals
                }
                
                for(m=0; m<grpMembers.length; m++) {        // remove the student from the group array
                    if(grpMembers[m] == studnr) {
                        grpMembers.splice(m, 1);
                    }
                } 
                message(item, " ble fjernet!");   
                $('body > section').load ('pages/viewAllStudents.php'); //reload content
            }
        });
    }
}